import PaginationBar from "../../components/paginationbar";

import React, {useEffect, useState} from 'react'
import {Pagination, Breadcrumb, Button, Space, Input, Form, Row, Col, Modal, Checkbox, Select} from 'antd'
import "./style.less"
import common from "../../common"
import Table from "antd/es/table"

function DashBoard(props) {

    const [dataList, setDataList] = useState([])
    const [boxDataList, setBoxDataList] = useState([
        {label: 'Apple', value: 1},
        {label: 'Pear', value: 2},
        {label: 'xxx', value: 3},
        {label: 'Orange', value: 4}])

    const [searchForm] = Form.useForm();
    let [search, setSearch] = useState({})       //搜索内容

    let [pagination, setPagination] = useState({
        total: 0,
        page: 1,
        limit: 10,
    })

    let [query, setQuery] = useState({});
    const [createModalVisible, setCreateModalVisible] = useState(false)
    const [editModalVisible, setEditModalVisible] = useState(false)
    const [boxList, setBoxList] = useState(["18", "12"])

    const [createForm] = Form.useForm();
    const [editForm] = Form.useForm();

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
        },
        {
            title: '看板名字',
            dataIndex: 'name',
        },
        {
            title: '操作',
            align: "center",
            width: 160,
            fixed: "right",
            render: (text, record, index) => {
                return (
                    <>
                        <Button type="link" onClick={() => {
                            getBoxs()
                            setEditModalVisible(true)
                            editForm.setFieldsValue(record)
                            // setBoxList(record.boxList)
                            console.log(record.boxList)    
                            console.log("boxDataList" + boxDataList)
                        }}>编辑</Button>

                        <Button type="link" onClick={() => {
                            common.confirm("确定要删除吗?", () => {
                                del(record.id)
                            })
                        }}>删除</Button>
                    </>
                )
            }
        }
    ];

    const init = () => {
        let params = {
            page: pagination.page,
            limit: pagination.limit,
            ...search
        }

        common.ajax("GET", "/front/dashboard/list", params).then(data => {
            for (let i = 0; i < data.list.length; i++) {
                let list = []
                for (let j = 0; j < data.list[i].boxList.length; j++) {
                    list.push(data.list[i].boxList[j].id)
                }
                data.list[i].boxList = list
            }
            setDataList(data.list)
            setPagination(data.pagination)
            editForm.setFieldsValue(data.list[0])

        })
    }

    const create = (data) => {
        common.loadingStart()
        common.ajax("POST", "/front/dashboard/create", data).then(res => {
            common.toast("操作成功")
            setCreateModalVisible(false)
            init()
            setEditModalVisible(true)

        }).finally(common.loadingStop)
    }

    // 获取盒子列表
    const getBoxs = () => {
        let params = {
            ...search,
            page: 1,
            limit: 100,
        }
        
        common.ajax("GET", "/front/box/list", params).then(data => {
            let boxlists = []
            let boxitem = {label: 1, value: 1}
            data.list.map(item => {
                boxitem = {label: item.name, value: item.id}
                boxlists.push(boxitem)
            })
            setBoxDataList(boxlists)
        })
    }

    const update = (data) => {
        let config = {contentType: "application/json"}
        common.loadingStart()
        common.ajax("POST", "/front/dashboard/update", data, config).then(res => {
            common.toast("操作成功")
            setEditModalVisible(false)
            init()
        }).finally(common.loadingStop)
    }

    const del = (id) => {
        common.loadingStart()
        common.ajax("POST", "/front/dashboard/delete", {id}).then(res => {
            common.toast("操作成功")
            init()
        }).finally(common.loadingStop)
    }
 

    function onChange(checkedValues) {
        console.log('checked = ', checkedValues);
    }

    useEffect(() => {
        init()
    }, [pagination.page, pagination.limit, search])

    return (
        <div className="DashBoard">

            <Breadcrumb>
                <Breadcrumb.Item>设备管理</Breadcrumb.Item>
                <Breadcrumb.Item>看板管理</Breadcrumb.Item>
            </Breadcrumb>

            <div style={{padding: 24, minHeight: 600}}>

                <div>
                    <Button type="primary" onClick={() => {
                        setCreateModalVisible(true)
                        createForm.setFieldsValue({title: ""})
                    }}>新增</Button>
                </div>

                <Form form={searchForm} style={{marginTop: 15}}>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item label="看板名字" name="name">
                                <Input placeholder="名字" onChange={(e) => {
                                    setQuery({...query, name: e.target.value})
                                }}/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item>
                                <Space>
                                    <Button onClick={() => {
                                        setSearch(query)
                                    }}>搜索</Button>

                                    <Button onClick={() => {

                                        let emptySearch = {
                                            name: '',
                                        }

                                        searchForm.setFieldsValue(emptySearch)
                                        emptySearch = {}
                                        setSearch(emptySearch)
                                        setQuery(emptySearch)
                                    }}>清空</Button>
                                </Space>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>

                <Table rowKey={columns => columns.id} dataSource={dataList} columns={columns} pagination={false}/>

                {pagination.total < 5 ? '' :
                    <PaginationBar>
                        <Pagination
                            style={{marginTop: 25}}
                            pageSizeOptions={['10', '20', '50', '100']}
                            onChange={(page, limit) => {
                                setPagination({...pagination, page, limit})
                            }}
                            onShowSizeChange={(page, limit) => {
                                setPagination({...pagination, page, limit})
                            }}
                            showTotal={total => `共${total}条`}
                            total={pagination.total}
                            defaultCurrent={pagination.page}
                            current={pagination.page}
                            defaultPageSize={pagination.limit}
                            showSizeChanger
                            showQuickJumper
                        /></PaginationBar>}

            </div>

            <Modal title="新增" destroyOnClose={true} footer={false} maskClosable={false} visible={createModalVisible}
                   onCancel={() => {
                       setCreateModalVisible(false)
                   }}
            >
                <Form preserve={false}
                      labelCol={{span: 6}}
                      wrapperCol={{span: 16}}
                      form={createForm}
                      onFinish={(values) => {
                          create(values)
                      }}
                >

                    <Form.Item
                        label="看板名字"
                        name="name"
                        rules={[{required: true, message: '请输入看版名称'}]}
                    >
                        <Input/>
                    </Form.Item>
                    <Form.Item wrapperCol={{offset: 6, span: 16}}>
                        <Button type="primary" htmlType="submit">
                            保存
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal title="编辑" footer={false} destroyOnClose={true} maskClosable={false} visible={editModalVisible}
                   onCancel={() => {
                       setEditModalVisible(false)
                   }}
            >
                <Form
                    labelCol={{span: 6}}
                    wrapperCol={{span: 16}}
                    form={editForm}
                    onFinish={(values) => {
                        let newBoxList = [];
                        values.boxList.map(item => {
                            newBoxList.push({id: item})
                        })
                        values.boxList = newBoxList
                        console.log(newBoxList)
                        update(values)

                    }}
                >
                    <Form.Item
                        hidden={true}
                        name="id"
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item
                        label="看板名字"
                        name="name"
                        rules={[{required: true, message: '请输入看板名字'}]}
                    >
                        <Input/>

                    </Form.Item>
                    <Form.Item name="boxList" label="所属盒子" className={"dashboardxxxx"}>
                        <Checkbox.Group options={boxDataList}/>
                    </Form.Item>
                    <Form.Item wrapperCol={{offset: 6, span: 16}}>
                        <Button type="primary" htmlType="submit">
                            保存
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}

export default DashBoard
